package com.nulldev.util.networking.npacket4.iprotocols.ncryptx;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import com.nulldev.util.VariableAPI.ByteUtil;
import com.nulldev.util.networking.npacket4.nPacket;
import com.nulldev.util.networking.npacket4.extensions.PacketExtension;

public class nCryptRequestKeyPair extends nPacket {

	private static final long serialVersionUID = -8075948351860595263L;

	public nCryptRequestKeyPair(final PacketExtension... exts) {
		super("ncryptx.request_key_pair", exts);
	}

	public nCryptRequestKeyPair(final nPacket packet) {
		super("ncryptx.request_key_pair", packet);
	}

	public nCryptRequestKeyPair(final int keyLengthPrimary, final PacketExtension... exts) {
		super("ncryptx.request_key_pair", exts);
		this.keyPrimary = ByteUtil.randomBytes(keyLengthPrimary);
	}

	public nCryptRequestKeyPair(final int keyLengthPrimary, final int keyLengthSecondary, final PacketExtension... exts) {
		super("ncryptx.request_key_pair", exts);
		this.keyPrimary = ByteUtil.randomBytes(keyLengthPrimary);
		this.keySecondary = ByteUtil.randomBytes(keyLengthSecondary);
	}

	private byte[] keyPrimary, keySecondary;

	@Override
	public void onGenerate(final DataOutputStream dos) throws IOException {
		if (keyPrimary == null || keyPrimary.length < 4)
			return;
		dos.writeInt(keyPrimary.length);
		dos.write(keyPrimary);
		final boolean isPair = (keySecondary != null && keySecondary.length >= 4);
		dos.writeBoolean(isPair);
		if (isPair) {
			dos.writeInt(keySecondary.length);
			dos.write(keySecondary);
		}
	}

	@Override
	public void onPacket(final DataInputStream dis) throws IOException {
		final int keyLength = dis.readInt();
		if (keyLength < 4)
			return;
		final byte[] d = new byte[keyLength];
		dis.read(d);
		this.keyPrimary = d;
		final boolean isPair = dis.readBoolean();
		if (isPair) {
			final int keyLength2 = dis.readInt();
			if (keyLength2 < 4)
				return;
			final byte[] d2 = new byte[keyLength2];
			dis.read(d2);
			this.keySecondary = d2;
		}
	}

	public byte[] keyPrimary() {
		return this.keyPrimary;
	}

	public byte[] keySecondary() {
		return this.keySecondary;
	}
}
